<template>
  <el-drawer
    v-model="infoOptions.show"
    title="标签信息"
    direction="ltr"
    :before-close="handleClose"
    @opened="openfn"
    size="85%"
    custom-class="drawer-info"
    :close-on-click-modal="false"
  >
    <div class="content" v-loading="loading">
      <div class="title" v-if="tableData.length > 0">
        <el-button type="success" @click="save" size="small">保 存</el-button>
        <el-button
          type="primary"
          @click="edit"
          v-permission="['labels:detail']"
          size="small"
          >编 辑</el-button
        >
        <el-button type="warning" @click="lookImg" size="small"
          >查看图片</el-button
        >
      </div>
      <div class="table-form">
        <hcTable
          :table-data="tableData"
          :options="options"
          :columns="tableColumn"
        >
          <template #paramName="{ row }">
            <span v-if="!editing">{{ row.paramName }}</span>
            <el-input v-model="row.paramName" v-else></el-input>
          </template>
          <template #paramType="{ row }">
            <span v-if="!editing">{{ row.paramType }}</span>
            <el-input v-model="row.paramType" v-else></el-input>
          </template>
          <template #paramValue="{ row }">
            <span v-if="!editing">{{ row.paramValue }}</span>
            <el-input v-model="row.paramValue" v-else></el-input>
          </template>
          <template #valueType="{ row }">
            <span v-if="!editing">{{ row.valueType }}</span>
            <el-input v-model="row.valueType" v-else></el-input>
          </template>
          <template #fontType="{ row }">
            <span v-if="!editing">{{ row.fontType }}</span>
            <el-input v-model="row.fontType" v-else></el-input>
          </template>
          <template #fontSize="{ row }">
            <span v-if="!editing">{{ row.fontSize }}</span>
            <el-input v-model="row.fontSize" v-else></el-input>
          </template>
          <template #charLenth="{ row }">
            <span v-if="!editing">{{ row.charLenth }}</span>
            <el-input v-model="row.charLenth" v-else></el-input>
          </template>
          <template #position="{ row }">
            <span v-if="!editing">{{ row.position }}</span>
            <el-input v-model="row.position" v-else></el-input>
          </template>
        </hcTable>
      </div>
    </div>
    <hcDialog
      draggable
      dialogWidth="60%"
      dialogTitle="标签图片"
      :isVisable="imgshow"
      @closeDialog="closeImg"
      @openDialog="openImg"
      top="2%"
    >
      <div class="img-can">
        <div class="tool">
          <div class="btns">
            <div class="c-item">
              <div class="text">边框颜色</div>
              <el-color-picker
                v-model="toolConfig.color"
                color-format="hex"
                class="clr"
              />
            </div>
            <div class="c-item">
              <div class="text">边框宽度</div>
              <el-input-number
                v-model="toolConfig.lineWidth"
                :min="1"
                size="small"
              ></el-input-number>
            </div>
            <div class="c-item">
              <el-button @click="changeConfig" type="primary" size="small"
                >确 定</el-button
              >
            </div>
          </div>

          <div class="btns">
            <el-button type="primary" @click="editRect" size="small"
              >{{ canEdit ? "只读模式" : "编辑模式" }}
            </el-button>

            <template v-if="canEdit">
              <el-button type="warning" @click="addData" size="small"
                >新增数据</el-button
              >
              <el-button type="danger" @click="delRect" size="small"
                >删除选中框</el-button
              >
            </template>
            <el-button type="success" @click="saveRect" size="small"
              >保存数据</el-button
            >
          </div>
        </div>
        <div class="can-con">
          <canvas ref="canvasref" width="500" height="400" class="can"></canvas>
        </div>
        <hcDialog
          draggable
          dialogWidth="30%"
          dialogTitle="数据绑定"
          :isVisable="rectDataShow"
          @closeDialog="closeSelect(false)"
          @openDialog="openSelect"
          top="5%"
        >
          <el-form>
            <el-form-item label="数据绑定">
              <el-select v-model="bindForm.bindValue" clearable>
                <el-option
                  v-for="(item, index) of unBindArr"
                  :label="item.label"
                  :value="item.value"
                  :key="index"
                  :title="item.value.paramName + '-' + item.value.paramValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="bindData">确 定</el-button>
            </el-form-item>
          </el-form>
        </hcDialog>
      </div>
    </hcDialog>
    <addDataDialog @closeDialog="addClose" :addDataShow="addDataShow" />
  </el-drawer>
</template>
<script setup>
import { reactive, ref } from "vue";
import { getLabelParams } from "@/api/labels";
import getEnvConfig from "@/config/axios/getEnvConfig";
import ImageMark from "@/utils/imageMark.js";
import { getUUID } from "@/utils";
import addDataDialog from "./addData.vue";

let props = defineProps({
  infoOptions: {
    type: Object,
    default: () => {},
  },
});

let emit = defineEmits(["closeDraw"]);

let options = {
  showPagination: false,
  border: true,
};

let imageMark = null; // 图片编辑器实例
let newAddRect = null; // 新添加的矩形
let hasBind = false; // 是否有数据绑定

let loading = ref(false);
let imgshow = ref(false);
let canEdit = ref(false);
let canvasref = ref();
let rectDataShow = ref(false); // 数据绑定弹窗
let addDataShow = ref(false); // 新增数据弹窗

let bindForm = reactive({
  bindValue: "",
});
let unBindArr = ref([]); // 未绑定的数据
let imgInfo = reactive({
  width: 0,
  height: 0,
  url: "",
  scale: (innerWidth / 1920) * 10,
});
let toolConfig = reactive({
  color: "#f00",
  lineWidth: 1,
});
let tableColumn = [
  { type: "index", width: "60", label: "序号", align: "center", fixed: true },
  {
    prop: "paramName",
    label: "字段名称",
    slot: "paramName",
    showOverflowTooltip: true,
  },
  { prop: "paramType", label: "字段属性", width: 100, slot: "paramType" },
  { prop: "paramValue", label: "字段内容", slot: "paramValue" },
  {
    prop: "valueType",
    label: "类型",
    width: 90,
    slot: "valueType",
    showOverflowTooltip: true,
  },
  { prop: "fontType", label: "字体格式", width: 90, slot: "fontType" },
  { prop: "fontSize", label: "字体大小", width: 90, slot: "fontSize" },
  { prop: "charLenth", label: "字符长度", width: 90, slot: "charLenth" },
  {
    prop: "position",
    label: "起始坐标",
    slot: "position",
    showOverflowTooltip: true,
  },
];

let editing = ref(false);

let tableData = ref([]);

function save() {
  editing.value = false;
}

function edit() {
  editing.value = true;
}

function lookImg() {
  imgshow.value = true;
}

function handleClose() {
  editing.value = false;
  tableData.value = [];
  emit("closeDraw");
}

async function openfn() {
  loading.value = true;
  let temp = props.infoOptions.data.labelTemplates;
  temp = temp.split("|")[0];
  tableData.value = [];
  let res = await getLabelParams({ labelTemplateName: temp });
  tableData.value = res?.labelPointNameDatas ?? [];
  imgInfo.width = res?.lablePhysicsWidth * imgInfo.scale ?? 0;
  imgInfo.height = res?.lablePhysicsHeight * imgInfo.scale ?? 0;
  imgInfo.url =
    getEnvConfig.VITE_BASE_URL.replace("api", "") +
    res?.labelImageName.replace(/\\/g, "/");
  loading.value = false;
}

function closeImg() {
  imgshow.value = false;
  canEdit.value = false;
  imageMark && imageMark.dispose();
}

function openImg() {
  drawImg();
}

function drawImg() {
  canvasref.value.width = imgInfo.width;
  canvasref.value.height = imgInfo.height;
  let rects = [];
  tableData.value.forEach((item) => {
    item.id = getUUID();
    if (item.position) {
      let arr = item.position.replace(/\(|\)/g, "").split("|");
      let [x, y] = arr[0].split(",");
      let [w, h] = arr[1].split(",");
      let angle = arr[2];
      // 添加 已经识别的边框
      rects.push({
        id: getUUID(),
        x: x * imgInfo.scale,
        y: y * imgInfo.scale,
        width: w * imgInfo.scale,
        height: h * imgInfo.scale,
        rotatable: true,
        rotateAngle: 0,
        data: item,
        isBind: true,
      });
    } else {
      // 没有被识别的数据
      item.isBind = false;
      let str = parseLable(item);
      unBindArr.value.push({
        label: item.paramName + "-" + str,
        value: item,
      });
    }
  });
  imageMark = new ImageMark({
    el: canvasref.value,
    width: imgInfo.width,
    height: imgInfo.height,
    imgUrl: imgInfo.url,
    rects: rects,
  });

  imageMark.on("add", (newrect) => {
    //新添加的边框需绑定数据
    if (unBindArr.value.length == 0) {
      removeRect(newrect, "没有未绑定的数据，无需添加边框");
      return;
    }
    newAddRect = newrect;
    rectDataShow.value = true;
  });
  imageMark.on("delete", (rect) => {
    // 删除的边框 把绑定的数据添加到未绑定数据数组
    rect.data.isBind = false;
    let str = parseLable(rect.data);

    unBindArr.value.push({
      label: rect.data.paramName + "-" + str,
      value: rect.data,
    });
  });
}

function removeRect(rect, msg) {
  ElMessage.warning(msg);
  imageMark.removeRect(rect);
}

function delRect() {
  if (!imageMark.pickRect) {
    ElMessage.warning("未选中边框");
    return;
  }
  imageMark.deleteRect();
}

function changeConfig() {
  imageMark.color = toolConfig.color;
  imageMark.lineWidth = toolConfig.lineWidth;
  imageMark.draw();
}

function addData() {
  addDataShow.value = true;
}
function editRect() {
  canEdit.value = !canEdit.value;
  imageMark.readonly = !canEdit.value;
}

function saveRect() {
  let scale = imgInfo.scale;
  tableData.value = imageMark.rects.map((item) => {
    let x = (item.x / scale).toFixed(1);
    let y = (item.y / scale).toFixed(1);
    let w = (item.width / scale).toFixed(0);
    let h = (item.height / scale).toFixed(0);
    let pstr = `(${x},${y})|(${w},${h})|(${item.rotateAngle})`;
    item.data.position = pstr;
    return item.data;
  });

  closeImg();
}

function openSelect() {
  bindForm.bindValue = "";
  hasBind = false;
}

function closeSelect() {
  if (!hasBind) {
    //直接关闭弹窗 移除新添加的边框
    removeRect(newAddRect, "未绑定数据");
  }
  rectDataShow.value = false;
  newAddRect = null;
}

function bindData() {
  if (!bindForm.bindValue) {
    ElMessage.warning("请选择数据绑定");
    return;
  }
  newAddRect.data = bindForm.bindValue;
  newAddRect.isBind = true;
  let index = unBindArr.value.findIndex(
    (item) => item.value.id == bindForm.bindValue.id
  );
  if (index > -1) {
    unBindArr.value.splice(index, 1);
  }
  hasBind = true;
  closeSelect(true);
}

function addClose(val) {
  addDataShow.value = false;
  if (val) {
    val.id = getUUID();
    let str = parseLable(val);
    unBindArr.value.push({
      label: val.paramName + "-" + str,
      value: val,
    });
  }
}

function parseLable(data) {
  let str =
    data.paramValue.length > 20
      ? data.paramValue.slice(20) + "..."
      : data.paramValue;
  return str;
}
</script>
<style scoped lang="scss">
.content {
  width: 100%;
  height: 100%;
  .title {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 40px;
  }
  .table-form {
    height: calc(100% - 40px);
    padding: 0px;
    padding-bottom: 10px;
  }
}
.img-can {
  .tool {
    display: flex;
    justify-content: space-around;
    .c-item {
      display: flex;
      align-items: center;
      min-width: 200px;
      margin-right: 10px;
      .text {
        padding-left: 5px;
        width: 100px;
        text-align: left;
      }
      :deep(.el-color-picker__trigger) {
        width: 100px;
      }
    }
    .btns {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }
  .can-con {
    display: flex;
    justify-content: center;
    align-items: center;
    .can {
      border: 1px solid #999;
    }
  }
}
:deep(.el-form-item__content) {
  justify-content: flex-end;
}
</style>
<style>
.el-drawer__header {
  padding: 10px;
  margin-bottom: 0;
}
.el-drawer__body {
  padding: 10px;
}
</style>
